<template>
    <div id="instructionInfo-content">
        <el-row class="form-content">
            <el-form label-width="69px">
                <el-row>
                    <el-col :span="5">
                        <el-form-item label="产品代码(名称):">
                            <el-select v-model="searchForm.fundCode" filterable clearable size="mini">
                                <el-option
                                    v-for="i in fundCodeSelectData"
                                    :key="i.fundCode"
                                    :label="i.fundCode + ' ' + i.fundNameSt"
                                    :value="i.fundCode"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item label="证券代码(名称):">
                            <el-select
                                v-model="searchForm.stockCode"
                                filterable
                                remote
                                :remote-method="getstockCodeList"
                                clearable
                                @clear="getstockCodeList('')"
                                size="mini"
                            >
                                <el-option
                                    v-for="i in stockCodeSelectData"
                                    :key="i.stockCode"
                                    :label="i.stockCode + ' ' + i.stockNameSt"
                                    :value="i.stockCode"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="委托方向:">
                            <el-select v-model="searchForm.orderDirection" clearable size="mini">
                                <el-option value="3" label="债券买入">债券买入 </el-option>
                                <el-option value="4" label="债券卖出">债券卖出 </el-option>
                            </el-select>

                            <!-- <el-select v-model="searchForm.orderDirection" clearable size="mini">
                                <el-option v-for="i in orderDirectionData" :key="i.dictKey" :label="i.dictKeyName" :value="i.dictKey"> </el-option>
                            </el-select> -->
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="证券类别:">
                            <el-select v-model="searchForm.stockType" filterable clearable size="mini">
                                <el-option v-for="item in stockType" :key="item.dictKey" :value="item.dictKey" :label="item.dictKeyName"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="业务类型:">
                            <el-select v-model="searchForm.businessType" clearable size="mini">
                                <el-option value="2" label="银行间业务"> </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="3">
                        <el-button type="primary" size="mini" @click="query">查询</el-button>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="5">
                        <el-form-item label="指令序号:">
                            <el-input size="mini" placeholder="" v-model="searchForm.instNo"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item label="指令状态:">
                            <el-select v-model="searchForm.instStatus" size="mini">
                                <!-- <el-option key="" value=""></el-option> -->
                                <el-option v-for="(value, key) in instructionStatus" :key="key" :value="key" :label="value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="4">
                        <el-form-item label="下达人:">
                            <el-select v-model="searchForm.directUser" filterable clearable size="mini">
                                <el-option
                                    v-for="item in orderUsers"
                                    :key="item.dictKey"
                                    :value="item.dictCode"
                                    :label="item.dictKey + ' ' + item.dictKeyName"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="下达日期:">
                            <el-date-picker
                                v-model="directDate"
                                type="date"
                                value-format="yyyyMMdd"
                                placeholder="请选择"
                                format="yyyy/MM/dd"
                                style="width: 100%"
                            >
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="7">
                        <el-button type="primary" size="mini" @click="handleButtonClick('layout')">布局设置</el-button>
                        <el-button size="mini" @click="handleButtonClick('hide')" v-show="SHOW_SECURITY">{{
                            hideVisible ? '展开' : '隐藏'
                        }}</el-button>
                    </el-col>
                </el-row>
                <el-row v-if="!hideVisible">
                    <el-col :span="5">
                        <el-form-item label="资产单元编号(名称):">
                            <el-select v-model="searchForm.assetCode" filterable clearable size="mini">
                                <el-option
                                    v-for="i in assetCodeSelectData"
                                    :key="i.assetCode"
                                    :label="i.assetCode + ' ' + i.assetName"
                                    :value="i.assetCode"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item label="组合编码(名称):">
                            <el-select v-model="searchForm.fundAcCode" filterable clearable size="mini">
                                <el-option
                                    v-for="i in fundAccountCodeSelectData"
                                    :key="i.fundAccountCode"
                                    :label="i.fundAccountCode + ' ' + i.fundAccountName"
                                    :value="i.fundAccountCode"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="15"></el-col>
                </el-row>
            </el-form>
        </el-row>
        <el-row class="table-content">
            <div style="height: calc(100% - 60px)">
                <vxe-table
                    :key="tableKey"
                    :header-cell-style="{ backgroundColor: '#e8f3ff', padding: '4px 0' }"
                    :footer-cell-style="{ backgroundColor: '#e8f3ff', padding: '4px 0' }"
                    :data="dataSource"
                    border
                    v-loading="tableLoading"
                    element-loading-text="加载中"
                    size="mini"
                    height="100%"
                    ref="table"
                    @cell-click="handleRow"
                    style="cursor: pointer"
                    highlight-current-row
                    highlight-hover-row
                    stripe
                    auto-resize
                    resizable
                    :sort-config="{
                        defaultSort: { field: sortProp, order: sortOrder, orders: ['desc', 'asc', null] },
                        remote: true,
                    }"
                    @sort-change="changeTableSort"
                    show-header-overflow
                >
                    <template v-for="(item, index) in showFieldList">
                        <vxe-column
                            show-overflow
                            :key="index + 'name'"
                            :title="item.content"
                            :field="item.id"
                            :min-width="item.minWidth"
                            :fixed="item.fixed"
                            :sortable="item.id == 'operate' ? false : true"
                        >
                            <template slot="header">
                                <span>{{ item.content }}</span>
                            </template>
                            <template slot-scope="scope">
                                <span v-if="item.id == 'operate'">
                                    <el-button type="text" @click.stop="handleUpdateInst(scope.row)" :disabled="handleDisabled(scope.row)"
                                        >修改</el-button
                                    >
                                    <el-button type="text" @click.stop="handleBtnDel(scope.row)" :disabled="handleDisabled(scope.row)"
                                        >撤单</el-button
                                    >
                                </span>
                                <span v-else-if="item.id == 'instStatus'">
                                    {{ instructionStatus[scope.row.instStatus] }}
                                </span>
                                <span v-else-if="item.id == 'orderPriceType'" style="float:right">
                                    {{ investPriceSelectData[scope.row.orderPriceType] }}
                                </span>

                                <span v-else-if="item.id == 'directTime'">
                                    {{ formatterDate(scope.row['directDate']) + ' ' + formatterTime(scope.row['directTime']) }}
                                </span>

                                <span v-else-if="item.id == 'firstSettleDate'" style="display:block;text-align:center">
                                    {{ formatterDate(scope.row['firstSettleDate']) }}
                                </span>

                                <span
                                    v-else-if="
                                        [
                                            'faceBalance',
                                            'fullPrice',
                                            'netBalance',
                                            'netPrice',
                                            'settlementBalance',
                                            'totalInterest',
                                            'orderAmount',
                                        ].includes(item.id)
                                    "
                                    style="float:right"
                                >
                                    {{ scope.row[item.id] != undefined ? numberFormat(scope.row[item.id], 2) : '--' }}
                                </span>
                                <span v-else-if="['orderPrice', 'orderBalance'].includes(item.id)" style="float:right">{{
                                    scope.row[item.id] != undefined ? numberFormat(scope.row[item.id], 2) : '--'
                                }}</span>

                                <span v-else-if="item.id === 'calculateValue' || item.id === 'thresholdValue'">
                                    {{ scope.row[item.id] != undefined ? numberFormat(scope.row[item.id]) : '--' }}
                                </span>
                                <span v-else>{{ scope.row[item.id] || '--' }}</span>
                            </template>
                        </vxe-column>
                    </template>
                </vxe-table>
            </div>
            <risk-pagination :paging="pages" @page-change="handleCurrentChange"></risk-pagination>
        </el-row>
        <el-row class="tab-content">
            <el-tabs v-model="activeKey" style="height: 100%">
                <el-tab-pane label="指令明细" name="detail" class="inst-detail">
                    <div style="height: 100%; padding: 4px 10px; width: 100%; overflow-x: auto">
                        <div class="detail-row">
                            <el-tooltip placement="top" :content="clickRecord.instNo">
                                <span>
                                    指令序号：<span style="color: blue">{{ clickRecord.instNo }}</span>
                                </span>
                            </el-tooltip>
                            <span
                                >指令状态：<span style="color: blue">{{ instructionStatus[clickRecord.instStatus] }}</span>
                            </span>
                            <el-tooltip placement="top" :content="clickRecord.directUserName">
                                <span>
                                    下达人：<span style="color: blue">{{ clickRecord.directUserName }} </span>
                                </span>
                            </el-tooltip>
                            <span>
                                下达时间：<span style="color: blue">
                                    {{ formatterDate(clickRecord.directDate) + ' ' + formatterTime(clickRecord.directTime) }}</span
                                >
                            </span>
                        </div>
                        <div class="detail-row">
                            <el-tooltip placement="top" :content="clickRecord.fundCode">
                                <span>
                                    产品代码：<span style="color: blue">{{ clickRecord.fundCode }}</span>
                                </span>
                            </el-tooltip>
                            <el-tooltip placement="top" :content="clickRecord.fundName">
                                <span
                                    >产品名称：<span style="color: blue">{{ clickRecord.fundName }}</span>
                                </span>
                            </el-tooltip>
                            <el-tooltip placement="top" :content="clickRecord.assetCode">
                                <span v-show="SHOW_SECURITY">
                                    资产单元编号：<span style="color: blue">{{ clickRecord.assetCode }}</span>
                                </span>
                            </el-tooltip>
                            <el-tooltip placement="top" :content="clickRecord.assetName">
                                <span v-show="SHOW_SECURITY">
                                    资产单元名称：<span style="color: blue">{{ clickRecord.assetName }}</span>
                                </span>
                            </el-tooltip>
                            <el-tooltip placement="top" :content="clickRecord.groupCode">
                                <span
                                    >组合编码：
                                    <span style="color: blue">{{ clickRecord.groupCode }} </span>
                                </span>
                            </el-tooltip>
                            <el-tooltip placement="top" :content="clickRecord.groupName">
                                <span>
                                    组合名称：<span style="color: blue"> {{ clickRecord.groupName || '--' }}</span>
                                </span>
                            </el-tooltip>
                            <el-tooltip placement="top" :content="clickRecord.stockCode">
                                <span>
                                    证券代码：<span style="color: blue">{{ clickRecord.stockCode || '--' }}</span>
                                </span>
                            </el-tooltip>
                            <el-tooltip placement="top" :content="clickRecord.stockName">
                                <span v-show="!SHOW_SECURITY">
                                    证券名称：<span style="color: blue">{{ clickRecord.stockName || '--' }}</span>
                                </span>
                            </el-tooltip>
                            <span v-show="!SHOW_SECURITY">
                                投资类型：<span style="color: blue">{{ clickRecord.investTypeName || '--' }}</span>
                            </span>
                        </div>

                        <div class="detail-row">
                            <el-tooltip placement="top" :content="clickRecord.stockName">
                                <span v-show="SHOW_SECURITY">
                                    证券名称：<span style="color: blue">{{ clickRecord.stockName || '--' }}</span>
                                </span>
                            </el-tooltip>
                            <span v-show="SHOW_SECURITY">
                                投资类型：<span style="color: blue">{{ clickRecord.investTypeName || '--' }}</span>
                            </span>
                            <span>
                                业务类型：<span style="color: blue">{{ clickRecord.businessTypeName || '--' }}</span>
                            </span>
                            <span
                                >委托方向：<span style="color: blue">{{ clickRecord.orderDirectionName || '--' }}</span>
                            </span>
                            <span>
                                币种：<span style="color: blue"> {{ clickRecord.curName }}</span>
                            </span>
                            <span>
                                交易市场：<span style="color: blue">{{ clickRecord.marketName }}</span>
                            </span>
                        </div>

                        <div class="detail-row">
                            <span
                                >券面总额(万元)：<span style="color: blue">{{
                                    clickRecord.faceBalance != undefined ? numberFormat(clickRecord.faceBalance, 4) : '--'
                                }}</span>
                            </span>
                            <span>
                                指令数量(张)：<span style="color: blue">{{
                                    clickRecord.orderAmount != undefined ? numberFormat(clickRecord.orderAmount, 2) : '--'
                                }}</span>
                            </span>
                            <span
                                >净价价格(元)：<span style="color: blue">{{
                                    clickRecord.netPrice != undefined ? numberFormat(clickRecord.netPrice, 2) : '--'
                                }}</span>
                            </span>
                            <span
                                >全价价格(元)：<span style="color: blue"
                                    >{{ clickRecord.fullPrice != undefined ? numberFormat(clickRecord.fullPrice, 2) : '--' }}
                                </span>
                            </span>
                            <span>
                                净价金额(元)：<span style="color: blue">
                                    {{ clickRecord.netBalance != undefined ? numberFormat(clickRecord.netBalance, 2) : '--' }}</span
                                >
                            </span>

                            <span>
                                总应计利息(元)：<span style="color: blue">{{
                                    clickRecord.totalInterest != undefined ? numberFormat(clickRecord.totalInterest, 2) : '--'
                                }}</span>
                            </span>
                            <span>
                                结算金额(元)：<span style="color: blue">{{
                                    clickRecord.settlementBalance != undefined ? numberFormat(clickRecord.settlementBalance, 2) : '--'
                                }}</span>
                            </span>
                        </div>

                        <div class="detail-row">
                            <span>
                                结算日期：<span style="color: blue">{{ formatterDate(clickRecord.firstSettleDate) || '--' }}</span></span
                            >

                            <span>
                                清算速度：<span style="color: blue">{{ this.Invest.clearSpeed[clickRecord.clearSpeed] || '--' }}</span>
                            </span>
                            <el-tooltip placement="top" :content="clickRecord.opponentName">
                                <span
                                    >交易对手：<span style="color: blue"> {{ clickRecord.opponentName || '--' }}</span>
                                </span>
                            </el-tooltip>
                        </div>
                    </div>
                </el-tab-pane>
                <el-tab-pane label="指令证券" name="stock">
                    <div style="height: 100%; padding: 4px 10px">
                        <risk-table :msg="instStockMsg" v-loading="tabsLoading"></risk-table>
                    </div>
                </el-tab-pane>

                <el-tab-pane label="指令结果" name="result">
                    <div style="height: 100%; padding: 4px 10px">
                        <risk-table
                            :msg="instResultMsg"
                            v-loading="tabsLoading"
                            @handleBtn="handleBtnLook"
                            :key="instResultMsgNumKey + 'instResultMsgNumKey'"
                            v-if="activeKey === 'result'"
                        ></risk-table></div
                ></el-tab-pane>
            </el-tabs>
        </el-row>

        <RiskTableLayout
            title="页面布局"
            :visible.sync="layoutDialog"
            :field-list="tableColumns"
            :selected-field-list="selectedFieldList"
            :fixed-field-list="fixedFieldList"
            table-name="BOND_TRIAL_CALCULATE"
            @on-submit="onSubmit"
        />

        <!-- <DeleteInvest
            :deleteBidShow="showDeleteInvst"
            :rowData="deleteRowData"
            @deleteBidReturn="deleteInvestReturn"
            v-if="showDeleteInvst"
        ></DeleteInvest> -->
    </div>
</template>
<script lang="ts">
import Invest from '@/common/dict/invest';
import DictionConstUtil, { SGU_CACHE } from '@/utils/diction-const-util';
import { dateFormat, PrefixInteger, timeFormat, numberFormat, UUID, sortBy, getConfigItem } from '@/utils/tools';
import moment from 'moment';
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import RiskTable from '@/common/components/risk-table.vue';
import ColumnUtil from '../utils/column-util';
import RiskIconButton from '@/common/components/risk-icon-button.vue';
import StatusTag from '@/pages/risk-measure/components/status-tag.vue';
import { getInstSelectOrderUser } from '@/pages/baseparam/api';
import RiskTableLayout from '@/common/components/risk-table-layout.vue';
import DeleteInvest from '../invest-manage/deleteInvest.vue';
import { getUser } from '@/utils/user-util';
import { getBusinessType } from '../api';
import RiskPagination from '@/common/components/risk-pagination.vue';
import InstructionInfoClass from '../class/instruction-info-class';

export interface pages {
    total?: number;
    pageSize?: number;
    currentPage?: number;
}
@Component({
    name: 'BankBondInstructionInfo',
    components: {
        RiskTable,
        RiskIconButton,
        StatusTag,
        RiskTableLayout,
        DeleteInvest,
        RiskPagination,
    },
})
export default class BankBondInstructionInfo extends InstructionInfoClass {
    @Prop()
    renderCount: number;
    numberFormat = numberFormat;
    ColumnUtil = new ColumnUtil();
    Invest: any = new Invest();
    SHOW_SECURITY = getConfigItem('SHOW_SECURITY');

    // 查询表单
    searchForm: any = {
        assetTypes: [],
        businessType: '',
        // directDate: Number(moment().format('YYYYMMDD')),
        directUser: '',
        fundCode: '',
        instNo: '',
        instStatus: '1',
        marketTypes: [],
        orderDirection: '',
        stockCode: '',
        stockType: '',
        stockTypes: [],
        assetCode: '',
        fundAcCode: '',
        sort: 'D_DIRECT_DATE' + ' ' + 'DESC' + ',' + 'D_DIRECT_TIME' + ' ' + 'DESC',
    };

    // 撤单表单
    cancelOrder: any = {
        cancelOrderType: '2',
        tradeUser: getUser().userCode, // 当前用户
        tradeUserName: getUser().userName, // 当前用户
        orderType: '4',
        instructionType: '10',
        instNo: '',
        originOuterOrderCode: '',
        outerOrderCode: UUID() + '-' + new Date().getTime(),
        requestId: UUID() + '-' + new Date().getTime(),
    };

    directDate: string = '';
    fundCodeSelectData: any[] = []; // 产品序号下拉框数据
    investPriceSelectData: any = {}; // 价格模式
    innerOrderDirectionData: any[] = [];
    orderDirectionData: any[] = []; // 委托方向数据

    listMsgNumKey: number = 0; // 指令数据Key
    dataSource: any[] = []; // 指令表数据

    pages: pages = {
        pageSize: 50,
        currentPage: 1,
        total: 0,
    };

    // 全部表格列
    tableColumns: any[] = [
        { content: '指令序号', id: 'instNo', minWidth: 120, fixed: 'left' },
        { content: '产品代码', id: 'fundCode', minWidth: 120 },
        { content: '产品名称', id: 'fundName', minWidth: 120 },
        { content: '组合编码', id: 'groupCode', minWidth: 150 },
        { content: '组合名称', id: 'groupName', minWidth: 150 },
        { content: '证券代码', id: 'stockCode', minWidth: 120 },
        { content: '证券名称', id: 'stockName', minWidth: 120 },
        { content: '业务类型', id: 'businessTypeName', minWidth: 120 },
        { content: '委托方向', id: 'orderDirectionName', minWidth: 120 },
        { content: '投资类型', id: 'investTypeName', minWidth: 120 },
        { content: '指令数量(张)', id: 'orderAmount', minWidth: 140 },
        { content: '币种', id: 'curCode', minWidth: 100 },
        { content: '交易市场', id: 'marketName', minWidth: 120 },

        { content: '券面总额(万元)', id: 'faceBalance', minWidth: 150 },
        { content: '净价价格(元)', id: 'netPrice', minWidth: 150 },
        { content: '全价价格(元)', id: 'fullPrice', minWidth: 150 },
        { content: '净价金额(元)', id: 'netBalance', minWidth: 150 },
        { content: '结算金额(元)', id: 'settlementBalance', minWidth: 150 },
        { content: '清算速度', id: 'clearSpeed', minWidth: 120 },
        { content: '结算日期', id: 'firstSettleDate', minWidth: 150, type: 'func', funcBody: value => dateFormat(value) || '--' },
        { content: '应计利息(元)', id: 'totalInterest', minWidth: 150 },
        { content: '下达人', id: 'directUserName', minWidth: 100 },
        { content: '交易对手', id: 'opponentName', minWidth: 100 },

        // { content: '下达人', id: 'directUser', minWidth: 100 },
        { content: '下达时间', id: 'directTime', minWidth: 120 },
        { content: '指令状态', id: 'instStatus', minWidth: 120, fixed: 'right' },
        { content: '操作', id: 'operate', minWidth: 120 },
    ];

    // 已选择字段列表(不包括固定字段)
    selectedFieldList: any[] = [];

    // 固定字段列表
    fixedFieldList: any[] = [
        { content: '指令序号', id: 'instNo', fixed: 'left', minWidth: 120 },
        { content: '指令状态', id: 'instStatus', minWidth: 120, fixed: 'right' },
        { content: '操作', id: 'operate', fixed: 'right', minWidth: 120 },
    ];

    showFieldList: any[] = []; // 要显示的表格列
    layoutDialog: boolean = false;

    activeKey: string = 'detail'; //  指令当前tabKey
    tableKey: number = 0;

    // 指令结果表格相关
    instResultMsg = {
        returnData: {},
        dataKey: 'list',
        title: this.ColumnUtil.instResultColumns,
        localSearch: true, // 本地搜索
        checked: { on: false, option: false },
        hidePage: true,
        height: '100%',
    };

    // 指令证券表格相关
    instStockMsg = {
        returnData: { list: [] },
        dataKey: 'list',
        title: this.ColumnUtil.instStockColumns,
        checked: { on: false, option: false },
        hidePage: true,
        height: '100%',
    };

    tableLoading: boolean = false; // 结果表数据加载
    selectLoading: boolean = false; // 下拉框远程搜索时的加载状态
    stockCodeSelectData: any[] = []; // 证券代码下拉框数据
    stockType: any[] = []; // 证券类别下拉
    instructionStatus = {
        '0': '已归档',
        '1': '已下达成功',
        '3': '已撤销',
        // '2': '已归档',
    };
    orderUsers: any[] = []; // 下单人下拉列表

    tabsLoading: boolean = false;

    stockLoading: boolean = false;
    clickRecord: any = {}; // 当前主表格点击的条目
    rowClickSetTime = null;
    instructionDetail: any = {};
    instStockDataSource: any[] = []; // 指令证券表数据
    instResultDataSource: any[] = []; // 指令结果表数据
    type: string = '';

    deleteRowData: any = {}; // 撤单行
    showDeleteInvst: boolean = false; // 撤单弹框

    sortProp: string = 'directTime'; // 排序字段
    sortOrder: string = 'descending'; // 排序方式
    commonField = this.ColumnUtil.commonFieldSort;

    extraField = {};
    marketCodes: any = {};

    @Watch('renderCount')
    onWatchRenderCount() {
        this.getInstruction(this.searchForm, this.pages);
    }

    hideVisible: boolean = true; // 是否隐藏
    assetCodeSelectData: any[] = [];
    fundAccountCodeSelectData: any[] = [];
    async mounted() {
        if (this.SHOW_SECURITY) {
            this.$axios.get('/asset/list/byFundCode').then((res: any) => {
                this.assetCodeSelectData = res;
            });
            this.$axios.get('/fdAc/list/byFundCode').then((res: any) => {
                this.fundAccountCodeSelectData = res;
            });
        }
        this.tableColumns = this.ColumnUtil.handleTableColumns(this.tableColumns, 'id');
        // 价格模式
        let priceTypeTemp = await SGU_CACHE('PriceType', '/dict/list/code/Y_000237', []);
        this.investPriceSelectData = DictionConstUtil.ListToPojo(priceTypeTemp);
        // 获取产品信息 (产品序号下拉框数据)
        this.fundCodeSelectData = await SGU_CACHE('FundInfoByUser', '/fundInfo/list/byUser/like', []);
        // 获取证券代码下拉框数据
        this.getstockCodeList('');
        // 证券类别
        this.stockType = await DictionConstUtil.FNStockType();
        // 下单人下拉列表
        this.$axios.post('instruction/user/select').then((res: any) => {
            this.orderUsers = res;
        });
        this.getInstruction(this.searchForm, this.pages);
        this.queryLayout();
        this.marketCodes = DictionConstUtil.ListToPojo(await DictionConstUtil.FNMarketType());
    }

    query() {
        this.searchForm.directDate = Number(this.directDate) || null;
        this.clickRecord = {};
        this.getInstruction(this.searchForm, { currentPage: 1, pageSize: 50 });
    }

    // 排序改变
    changeTableSort(column: any): void {
        this.sortProp = column.property;
        this.sortOrder = column.order;
        let sortType = column.order == 'asc' ? 'ASC' : column.order == 'desc' ? 'DESC' : '';
        if (sortType) {
            this.searchForm.sort = this.findName(column.property, sortType);
        } else {
            this.searchForm.sort = 'D_DIRECT_DATE ' + 'DESC' + ',' + 'D_DIRECT_TIME ' + 'DESC';
        }
        this.getInstruction(this.searchForm, this.pages);
    }

    // 获取排序字段名称
    findName(name: string, order: string): string {
        let value = '';
        let field = '';
        let allFields = { ...this.commonField, ...this.ColumnUtil.bankZQFieldSort };

        if (name === 'directTime') {
            value = 'D_DIRECT_DATE' + ' ' + order + ',' + 'D_DIRECT_TIME' + ' ' + order;
        } else {
            for (const key in allFields) {
                if (name === key) {
                    field = allFields[key];
                }
            }
            value = field + ' ' + order;
        }
        return value;
    }

    getInstruction(param: any, pages: any) {
        this.tableLoading = true;
        this.$axios
            .post('instruction/bankStockInstruction', {
                ...this.searchForm,
                paging: {
                    currentPage: pages.currentPage,
                    pageSize: pages.pageSize,
                },
            })
            .then((res: any) => {
                this.dataSource = res.list;
                this.pages.total = res.total;
                if (this.dataSource.length) {
                    this.clickRecord = this.dataSource[0] || {};
                    // if (moment(this.clickRecord.directDate).isBefore(moment().format('YYYYMMDD'))) {
                    //     this.type = 'history';
                    // } else {
                    //     this.type = '';
                    // }
                    if (this.clickRecord.instStatus == '0') {
                        this.type = 'history';
                    } else {
                        this.type = '';
                    }
                    (this.$refs['table'] as any).setCurrentRow(this.dataSource[0]);
                    this.handleRow({ row: this.clickRecord });
                } else {
                    this.$set(this.instStockMsg.returnData, 'list', []);
                    this.$set(this.instResultMsg.returnData, 'list', []);
                }
                this.tableLoading = false;
            })
            .catch(() => {
                this.tableLoading = false;
            });
    }

    // 获取证券代码下拉框数据
    getstockCodeList(value: string) {
        this.selectLoading = true;
        this.$axios
            .post('/dict/stock/report/select/' + 3, {
                dictKey: value,
                dictKeyName: value,
            })
            .then((res: any) => {
                this.stockCodeSelectData = res || [];
                this.selectLoading = false;
            });
    }

    // 格式化日期
    formatterDate(cellValue) {
        return cellValue ? dateFormat(cellValue) : '';
    }

    //  格式化时间
    formatterTime(cellValue) {
        return cellValue ? timeFormat(cellValue) : '';
    }

    // 修改指令
    handleUpdateInst(row: any) {
        this.$emit('changeTab', row);
    }

    // 查看按钮点击
    handleBtnLook(obj: any): void {
        this.$emit('handelOperate', { record: obj.row, history: this.type === 'history', clickRecord: this.clickRecord });
    }

    // 撤单事件
    handleBtnDel(row: any): void {
        // this.deleteRowData = row;
        this.cancelOrder.instNo = row.instNo;
        this.cancelOrder.originOuterOrderCode = row.outerOrderCode;
        this.$confirm('确认是否撤单?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        })
            .then(() => {
                this.$axios
                    .post('/dataEngine/order/cancelOrder', this.cancelOrder)
                    .then((res: any) => {
                        this.yh_message_success('撤单成功');
                        this.getInstruction(this.searchForm, { currentPage: 1, pageSize: this.pages.pageSize });
                    })
                    .catch(() => {
                        this.yh_message_error('撤单失败');
                    });
            })
            .catch(() => {
                this.yh_message_info('已取消撤单');
            });
    }

    // 设置是否禁用
    handleDisabled(row: any): boolean {
        let userCode = getUser().userCode;
        return !(row['instStatus'] == '1' && (userCode == row.directUser || getUser().superuser));
    }

    // 按钮点击
    handleButtonClick(action: string): void {
        if (action === 'layout') {
            this.layoutDialog = true;
        } else if (action === 'hide') {
            this.hideVisible = !this.hideVisible;
            console.log(this.hideVisible, 'hideVisible');
        }
    }

    handleRow({ row }): void {
        this.clickRecord = row;
        this.currentClickRow = row;

        if (row.instStatus == '0') {
            this.type = 'history';
        } else {
            this.type = '';
        }
        this.getInstructionInfo();
    }

    // 点击单行
    // handleRow({ row }): void {
    //     this.clickRecord = row;
    //     this.currentClickRow = row;

    //     const form = {
    //         serialNo: this.currentClickRow.serialNo, // 流水号
    //         instNo: this.currentClickRow.instNo, // 指令序号
    //         outOrderCode: this.currentClickRow.outerOrderCode, // 外部指令序号
    //         showError: true, // 产品true, 浦银false
    //         dailyInstructionNo: 0, // 恒生指令序号
    //         indexDailyModify: 0, // 恒生指令修改次序
    //         sourceType: 1, // 数据来源类型 (判断是否外部指令下达)，这里默认查询内部指令
    //     };

    //     if (row.instStatus == '0') {
    //         this.type = 'history';
    //     } else {
    //         this.type = '';
    //     }
    //     let record = row;
    //     // 点击行
    //     this.tabsLoading = true;
    //     this.stockLoading = true;
    //     if (this.rowClickSetTime) {
    //         clearTimeout(this.rowClickSetTime);
    //         this.rowClickSetTime = null;
    //     }
    //     this.rowClickSetTime = setTimeout(() => {
    //         let isHistory = this.type === 'history';
    //         let url = '';
    //         if (isHistory) {
    //             url = '/instruction/inst/history/all/new';
    //         } else {
    //             url = '/instruction/inst/all/new';
    //         }
    //         // if (isHistory) {
    //         //     url = '/instruction/inst/history/all/' + record.instNo + '/' + record.outerOrderCode;
    //         // } else {
    //         //     url = '/instruction/inst/all/' + record.instNo + '/' + record.outerOrderCode;
    //         // }
    //         this.$axios.post(url, form).then((res: any) => {
    //             let instStockDataSource = [];
    //             if (res.deposits && res.deposits.length > 0) {
    //                 instStockDataSource = instStockDataSource.concat(res.deposits);
    //             }
    //             if (res.repos && res.repos.length > 0) {
    //                 instStockDataSource = instStockDataSource.concat(res.repos);
    //             }
    //             if (res.stocks && res.stocks.length > 0) {
    //                 instStockDataSource = instStockDataSource.concat(res.stocks);
    //             }
    //             instStockDataSource.forEach((item, i) => (item.key = item.serialNo + '-' + i));
    //             if (res.pleds && res.pleds.length > 0) {
    //                 res.pleds.forEach((item, i) => (item.key = item.serialNo + '-' + i));
    //             }
    //             if (res.results && res.results.length > 0) {
    //                 res.results.forEach((item, i) => (item.key = item.entryCode + '-' + i));
    //                 res.results = res.results.sort(sortBy('thresholdType', 'desc'));
    //             }
    //             this.tabsLoading = false;
    //             this.stockLoading = false;
    //             this.instructionDetail = record;
    //             this.instStockDataSource = instStockDataSource;
    //             this.$set(this.instStockMsg.returnData, 'list', this.instStockDataSource);
    //             this.instStockMsg.returnData.list.forEach(ele => {
    //                 ele.marketCode = this.marketCodes[ele.marketCode];
    //             });
    //             this.instResultDataSource = res.results;
    //             // this.instResultDataSource = res.results.filter((item: any) => item.thresholdType !== '4');
    //             this.$set(this.instResultMsg.returnData, 'list', this.instResultDataSource);
    //         });
    //     }, 500);
    // }

    // 分页
    handleCurrentChange(): void {
        this.getInstruction(this.searchForm, this.pages);
    }

    async onSubmit(data) {
        await this.queryLayout();
    }

    // 获取页面布局信息
    async queryLayout() {
        // this.tableLoading = true;
        let resList: any = await new Promise((resolve, reject) => {
            this.$axios('/tableLayout/query/BOND_TRIAL_CALCULATE')
                .then((res: any) => {
                    resolve(res);
                })
                .catch(err => {
                    reject(err);
                });
        });
        if (resList) {
            this.selectedFieldList = JSON.parse(resList);
            // 新增固定列 考虑到该列已被存入数据库问题
            this.selectedFieldList = this.selectedFieldList.filter(item => {
                let distinctIds = this.fixedFieldList.filter(fixedFieldListItem => {
                    return fixedFieldListItem.id === item.id;
                });
                if (distinctIds.length > 0) {
                    return false;
                } else {
                    return true;
                }
            });
            this.showFieldList = this.fixedFieldList.concat(this.selectedFieldList);
            this.showFieldList = this.showFieldList.filter(ele => !['orderPriceType', 'orderPrice', 'orderBalance'].includes(ele.id));
            this.tableKey++;
            // this.tableLoading = false;
        } else {
            this.showFieldList = this.tableColumns;
            this.selectedFieldList = this.tableColumns;
            this.tableKey++;
            // this.tableLoading = false;
        }
    }
}
</script>
<style lang="scss" scoped>
@import '@/pages/risk-time/styles/inst-info';
</style>
